import React, { PureComponent } from 'react';
import { connect } from 'dva';
import {
  Form,
  Input,
  Button,
  Card,
  Icon,
  Upload,
  notification,
  message,
  Progress,
} from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from './style.less';

const UNI_SIZE = "large";
const FormItem = Form.Item;
const infoTypeMap = {video: '视频', file: '文件', photo: '图片'};
const infoTypeCodeMap = {video: '1', file: '2', photo: '3'};
const infoExtMap = {video: ['mp4','ogg','webm','mov'], file: ['xls','xlsx','csv','docx'], photo: ['jpg','png','gif','bmp','png']};

const basePath = `${window.location.protocol}//${window.location.hostname}`;
function getFileUrl(fileName) {
  return `${basePath}/track/Uploads/temp/${fileName}`;
}

function getAcceptHelp(extList) {
  return extList.join('/');
}

function getAccept(extList) {
  return extList.map(item => ` .${item}`).join(',');
}

export default
@connect(({ loading }) => ({
  submitting: loading.effects['post/create'],
}))
@Form.create()
class BasicForms extends PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      thumbUrl: '',
      fileUrl: '',
      uploadingThumb: false,
      uploadingFile: false,
      curFileName: false,
      uploadProgress: 0,
    };
  }

  handleUploadThumb = (info) => {
    if (info.file.status === 'uploading') {
      this.setState({ uploadingThumb: true });
      return;
    }
    if (info.file.status === 'done') {
      const {response} = info.file;
      if(response.status === 1) {
        notification.success({message: response.info});
        this.setState({ thumbUrl: response.data.savename, uploadingThumb: false });
      } else {
        notification.error({message: response.info, description: response.data, duration: 10});
      }
      this.setState({ uploadingThumb: false });
    }
  }

  beforeUpload = () => {
    this.setState({ uploadingFile: false, uploadProgress: 0, fileUrl: '', curFileName: '' });
  }

  handleUploadFile = (info) => {
    if (info.file.status === 'uploading') {
      if(info.event && info.event.percent) {
        this.setState({ uploadProgress: Math.ceil(info.event.percent) });
      }
      this.setState({ uploadingFile: true });
      return;
    }
    if (info.file.status === 'done') {
      const {response} = info.file;
      if(response.status === 1) {
        notification.success({message: response.info});
        this.setState({ fileUrl: response.data.savename, uploadingFile: false, curFileName: info.file.name });
      } else {
        notification.error({message: response.info, description: response.data, duration: 10});
      }
      this.setState({ uploadingFile: false, uploadProgress: 0 });
    }
  }

  handleSubmit = e => {
    const { dispatch, form } = this.props;
    const {thumbUrl, fileUrl} = this.state;
    e.preventDefault();
    const infoType = window.location.href.split('/').pop();
    if(!thumbUrl) {
      message.error('请上传缩略图');
      return;
    }
    if(!fileUrl) {
      const typeStr = infoTypeMap[infoType];
      message.error(`请上传${typeStr}`);
      return;
    }
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const params = {
          ...values,
          post_thumb_url: thumbUrl,
          post_file_url: fileUrl,
          post_type: infoTypeCodeMap[infoType],
        }
        dispatch({
          type: 'post/create',
          payload: {
            data: params,
          },
        });
      }
    });
  };

  render() {
    const {thumbUrl, fileUrl, uploadingThumb, uploadingFile, curFileName, uploadProgress} = this.state;
    const { submitting, loading } = this.props;
    const {
      form: { getFieldDecorator },
    } = this.props;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 10 },
      },
    };

    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 10, offset: 7 },
      },
    };

    const uploadButton = (
      <div>
        <Icon type={uploadingThumb ? 'loading' : 'plus'} />
        <div className="ant-upload-text">选择文件</div>
      </div>
    );

    const infoType = window.location.href.split('/').pop();
    const infoTypeStr = infoTypeMap[infoType];
    const {protocol, hostname} = window.location;
    const uploadThumbUrl = `${protocol}//${hostname}/track/index.php/Post/uploadThumb`;
    const upperCasedInfoType = infoType[0].toUpperCase() + infoType.slice(1);
    const uploadUrl = `${protocol}//${hostname}/track/index.php/Post/upload${upperCasedInfoType}`;
    const uploadHelp = getAcceptHelp(infoExtMap[infoType]);
    const uploadAccept = getAccept(infoExtMap[infoType]);

    return (
      <PageHeaderWrapper>
        <Card bordered={false}>
          <Form onSubmit={this.handleSubmit} hideRequiredMark style={{ marginTop: 8 }}>
            <FormItem {...formItemLayout} label="主标题">
              {getFieldDecorator('post_title', {
                rules: [
                  {
                    required: true,
                    message: '请输入主标题',
                  },
                  {
                    max: 40,
                    message: '最多支持40个字符',
                  },
                ],
              })(<Input size={UNI_SIZE} placeholder="最多支持40个字符" />)}
            </FormItem>
            <FormItem {...formItemLayout} label="副标题">
              {getFieldDecorator('post_subtitle', {
                rules: [
                  {
                    required: true,
                    message: '请输入副标题',
                  },
                  {
                    max: 40,
                    message: '最多支持40个字符',
                  },
                ],
              })(<Input size={UNI_SIZE} placeholder="最多支持40个字符" />)}
            </FormItem>
            <FormItem {...formItemLayout} label="缩略图" help="转发消息时显示的缩略图">
              <Upload
                accept="image/*"
                name="avatar"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action={uploadThumbUrl}
                onChange={this.handleUploadThumb}
              >
                {thumbUrl ? <img src={getFileUrl(thumbUrl)} className={styles.uploadImage} alt="avatar" /> : uploadButton}
              </Upload>
            </FormItem>
            <FormItem {...formItemLayout} label={`${infoTypeStr}上传`} help={`支持${uploadHelp}文件`}>
              <Upload
                accept={uploadAccept}
                name="file"
                action={uploadUrl}
                beforeUpload={this.beforeUpload}
                onChange={this.handleUploadFile}
                showUploadList={false}
              >
                <Button disabled={uploadingFile}><Icon type="upload" /> 选择{infoTypeStr}</Button>
                {uploadingFile && uploadProgress ? <Progress percent={uploadProgress} size="small" /> : null}
                {curFileName ? <span style={{marginLeft: 8}}><Icon type="check" theme="outlined" style={{color: 'green'}} /> {curFileName}</span> : null}
              </Upload>
            </FormItem>
            <FormItem {...formItemLayout} label="内页标题">
              {getFieldDecorator('post_body_title', {
                rules: [
                  {
                    required: true,
                    message: '请输入内页标题',
                  },
                  {
                    max: 40,
                    message: '最多支持40个字符',
                  },
                ],
              })(<Input size={UNI_SIZE} placeholder="最多支持40个字符" />)}
            </FormItem>
            <FormItem {...formItemLayout} label="内页描述">
              {getFieldDecorator('post_body_desc', {
                rules: [
                  {
                    max: 500,
                    message: '最多支持500个字符',
                  },
                ],
              })(<Input.TextArea size={UNI_SIZE} rows={5} placeholder="最多支持500个字符" />)}
            </FormItem>
            <FormItem {...submitFormLayout} style={{ marginTop: 32 }}>
              <Button size="large" type="primary" htmlType="submit" loading={submitting}>
                提交
              </Button>
            </FormItem>
          </Form>
        </Card>
      </PageHeaderWrapper>
    );
  }
}
